<?php
/**
 * Created by PhpStorm.
 * User: Jiarui
 * Date: 2015/11/18
 * Time: 9:57
 */

namespace Admin\Controller;
use Think\Controller;

class SystemController extends BaseController
{
    public function _initialize(){
        parent::_initialize();

        $fpath = dirname(__FILE__);
        $fps = explode(DIRECTORY_SEPARATOR,$fpath);
        $len = count($fps);
        unset($fps[$len-1]);
        unset($fps[$len-2]);
        unset($fps[$len-3]);

        define('__PUBLIC__',implode(DIRECTORY_SEPARATOR,$fps).DIRECTORY_SEPARATOR.'Public');

    }

    public function listPage(){

        $settingModel = D('Setting');

        $homePage = $settingModel->getHomePage();

        $code = $settingModel->getCodeGZ();

        $this->assign('homePage1',$homePage['homePage1']);

        $this->assign('homePage2',$homePage['homePage2']);

        $this->assign('homePage3',$homePage['homePage3']);

        $this->assign('homePage4',$homePage['homePage4']);

        $this->assign('codeValue',$code);

        $this->display();

    }

    public function saveHomePage(){

        $id = I('get.id/d');

        $type = I('get.type/d');

        $temp = D('Route')->getRouteById($id);

        $img_url = $temp['img_url'];

        $result = D('Setting')->saveHomePage($type,$img_url,$id);

        $this->ajaxReturn($result);

    }

    public function deletePage(){

        $type = I('get.type/d');

        $model = D('setting');

        $result = $model->deletePage($type);

        if($result == 'ok'){

            $this->ajaxReturn('success');

        }else if($result == 'noExist'){

            $this->ajaxReturn('noExist');

        }else{

            $this->ajaxReturn('fail');

        }

    }

    public function uploadImg(){



        @set_time_limit(5 * 60);

        $targetDir = __PUBLIC__.DIRECTORY_SEPARATOR.'uploads_tmp';

        $cleanupTargetDir = true; // Remove old files
        $maxFileAge = 5 * 3600; // Temp file age in seconds

        if (!file_exists($targetDir)) {
            @mkdir($targetDir);
        }

        $targetDir = $targetDir.DIRECTORY_SEPARATOR.'system';


        if (!file_exists($targetDir)) {
            @mkdir($targetDir);
        }

        if (isset($_REQUEST["name"])) {
            $fileName = $_REQUEST["name"];
        } elseif (!empty($_FILES)) {
            $fileName = $_FILES["file"]["name"];
        } else {
            $fileName = uniqid("file_");
        }

//        $fileName .= time();

        $filePath = $targetDir . DIRECTORY_SEPARATOR . $fileName;

        $chunk = isset($_REQUEST["chunk"]) ? intval($_REQUEST["chunk"]) : 0;

        if ($cleanupTargetDir) {

            if (!is_dir($targetDir) || !$dir = opendir($targetDir)) {

                $this->ajaxReturn($targetDir.'---'.$dir.'{"code": 100, "message": "Failed to open temp directory."}, "id" : "id"}');

            }

            while (($file = readdir($dir)) !== false) {
                $tmpfilePath = $targetDir . DIRECTORY_SEPARATOR . $file;

                if ($tmpfilePath == "{$filePath}_{$chunk}.part" || $tmpfilePath == "{$filePath}_{$chunk}.parttmp") {
                    continue;
                }

                if (preg_match('/\.(part|parttmp)$/', $file) && (@filemtime($tmpfilePath) < time() - $maxFileAge)) {
                    @unlink($tmpfilePath);
                }
            }
            closedir($dir);
        }


        if (!$out = @fopen("{$filePath}_{$chunk}.parttmp", "wb")) {
            die('{"jsonrpc" : "2.0", "error" : {"code": 102, "message": "Failed to open output stream."}, "id" : "id"}');
        }

        if (!empty($_FILES)) {
            if ($_FILES["file"]["error"] || !is_uploaded_file($_FILES["file"]["tmp_name"])) {
                die('{"jsonrpc" : "2.0", "error" : {"code": 103, "message": "Failed to move uploaded file."}, "id" : "id"}');
            }

            // Read binary input stream and append it to temp file
            if (!$in = @fopen($_FILES["file"]["tmp_name"], "rb")) {
                die('{"jsonrpc" : "2.0", "error" : {"code": 101, "message": "Failed to open input stream."}, "id" : "id"}');
            }
        } else {
            if (!$in = @fopen("php://input", "rb")) {
                die('{"jsonrpc" : "2.0", "error" : {"code": 101, "message": "Failed to open input stream."}, "id" : "id"}');
            }
        }

        while ($buff = fread($in, 4096)) {
            fwrite($out, $buff);
        }

        @fclose($out);
        @fclose($in);

        $eName = I('post.id1').time();

        $fileP = $targetDir.DIRECTORY_SEPARATOR.$eName;

        rename("{$filePath}_{$chunk}.parttmp", "{$fileP}_{$chunk}.part");

        $this->ajaxReturn("{$eName}_{$chunk}.part");

    }

    public function saveCodeGZ(){
        $tmp_name = I('post.image_name/s');

        $result = D('Setting')->updateCode($tmp_name);

        if($result)
            $this->ajaxReturn('设置成功');
        else
            $this->ajaxReturn('出错，设置失败');
    }
}